package com.express.e.root.controller;

import com.express.e.root.annotation.ResponseBody;
import com.express.e.root.annotation.ResponseView;
import com.express.e.root.bean.Admin;
import com.express.e.root.bean.Message;
import com.express.e.root.enums.DeliveryEnum;
import com.express.e.root.service.AdminService;
import com.express.e.root.service.impl.AdminServiceImpl;
import com.express.e.root.utils.AdminWrap;
import com.express.e.root.utils.DeliveryWrap;
import com.express.e.root.utils.FomatDateUtil;
import com.express.e.root.utils.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class AdminController {
    private AdminService adminService = new AdminServiceImpl();

    @ResponseView(value = "/admin/login.do")
    public void loginIn(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("userName");
        String pwd = req.getParameter("pwd");


        Admin admin4login = new Admin();
        admin4login.setAdminName(userName);
        admin4login.setAdminPwd(pwd);

        Admin admin = adminService.loginIn(admin4login);
        if (null == admin || admin.getAdminName()==null || admin.getAdminName().isEmpty()) {
            resp.getWriter().write("<script>alert('login failed');location.href='/admin/index.jsp';</script>");
            return;
        } else {
            req.getSession().setAttribute("username", userName);
            req.getSession().setAttribute("pwd", pwd);
            req.getSession().removeAttribute("adminName");
            req.getSession().removeAttribute("adminPwd");
            req.getSession().removeAttribute("usersname");
            req.getSession().removeAttribute("userspwd");
            req.getRequestDispatcher("index.jsp").forward(req, resp);
        }
    }

    @ResponseView(value = "/admin/loginOut.do")
    public void loginOut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userName = req.getParameter("userName");
        String pwd = req.getParameter("pwd");

        Admin admin4loginOut = new Admin();
        admin4loginOut.setAdminName(userName);
        admin4loginOut.setAdminPwd(pwd);

        if (adminService.loginOut(admin4loginOut) == false) {
            resp.getWriter().write("<script>alert('Exit failed');location.href='/admin/index.jsp';</script>");
        } else {
            req.getSession().removeAttribute("username");
            req.getSession().removeAttribute("pwd");
            req.getSession().setMaxInactiveInterval(1);
            resp.sendRedirect("login.html");
        }

    }



    @ResponseBody("/admin/list.do")
    public String adminList(HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        List<Admin> admins = adminService.adminList();
        List adminsNew = new ArrayList<>();
        for (Admin d :
                admins) {
            AdminWrap adminWrap = new AdminWrap();
            adminWrap.setAdminId(d.getAdminId());
            adminWrap.setAdminName(d.getAdminName());
            adminWrap.setAdminPwd(d.getAdminPwd());
            adminWrap.setLoginIP(d.getLoginIP());
            adminWrap.setPhone(d.getPhone());
            adminWrap.setCardId(d.getCardId());
            adminWrap.setState(d.getState() == 1 ? "启用" : "禁用");
            adminWrap.setRole(d.getRole() == 0 ? "快递管理员" : "快递员");
            adminWrap.setLastTime(FomatDateUtil.formatDate(d.getLastTime()));
            adminsNew.add(adminWrap);
        }
        if (adminsNew != null) {
            String toJson = JSONUtil.toJson(new Message(200, "查找快递员成功！", adminsNew));
            System.out.println(toJson);
            return toJson;
        } else {
            String toJson = JSONUtil.toJson(new Message(400, "查找快递员失败！", adminsNew));
            System.out.println(toJson);
            return toJson;
        }
    }



    @ResponseBody("/admin/add.do")
    public String adminAdd(HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        String pwd = request.getParameter("pwd");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String cardId = request.getParameter("cardId");
        Admin admin = adminService.addAdmin(
                new Admin(
                        name,
                        pwd,
                        "127.0.0.1",
                        new Date(System.currentTimeMillis()),
                        0,
                        1,
                        phone,
                        cardId
                ));
        if (null == admin || admin.getAdminName().isEmpty()) {
            return JSONUtil.toJson(new Message(400, "增加失败", null));
        }
        AdminWrap adminWrap = new AdminWrap(
                admin.getAdminId(),
                admin.getAdminName(),
                admin.getAdminPwd(),
                admin.getLoginIP(),
                FomatDateUtil.formatDate(admin.getLastTime()),
                admin.getState() == 1 ? "启用" : "禁用",
                admin.getRole() == 0 ? "快递管理员" : "快递员",
                admin.getPhone(),
                admin.getCardId()
        );
        ArrayList<Object> objects = new ArrayList<>();
        objects.add(adminWrap);
        String insert = JSONUtil.toJson(new Message(200, "新增成功", objects));
        System.out.println(insert);
        return insert;
    }



    @ResponseBody("/admin/update.do")
    public String adminUpdate(HttpServletRequest req, HttpServletResponse resp) {
        resp.setCharacterEncoding("utf-8");
        String temp = req.getParameter("adminId");
        Integer adminId = -1;
        if (temp != null) {
            adminId = Integer.valueOf(temp);
        }
        String adminName = req.getParameter("adminName");
        String phone = req.getParameter("phone");
        String cardId = req.getParameter("cardId");
        String adminPwd = req.getParameter("adminPwd");
        Admin admin = adminService.queryById(adminId);
        if (null != admin &&admin.getAdminName()!=null) {
            Admin adminUpdate = new Admin(
                    adminId,
                    adminName,
                    adminPwd,
                    phone,
                    cardId
            );
            Admin adminResult = adminService.updateAdmin(adminUpdate);
            ArrayList<Object> objects = new ArrayList<>();
            objects.add(adminResult);
            String toJson = JSONUtil.toJson(new Message(200, "修改成功", objects));
            System.out.println(toJson);
            return toJson;
        }
        return JSONUtil.toJson(new Message(400, "修改失败", null));
    }


    @ResponseBody("/admin/findByPhone.do")
    public String findByPhone(HttpServletRequest req, HttpServletResponse resp) {
        resp.setCharacterEncoding("utf-8");
        String phone = req.getParameter("phone");
        System.out.println(phone);
        if (phone.isEmpty()) {
            return JSONUtil.toJson(new Message(401, "手机号码为空！", null));
        }
        Admin admin = adminService.queryByPhone(phone);
        System.out.println(admin.toString());
        if (null != admin && admin.getAdminName()!=null && !admin.getAdminName().isEmpty()) {
            AdminWrap adminWrap = new AdminWrap(
                    admin.getAdminId(),
                    admin.getAdminName(),
                    admin.getAdminPwd(),
                    admin.getLoginIP(),
                    FomatDateUtil.formatDate(admin.getLastTime()),
                    admin.getState() == 1 ? "启用" : "禁用",
                    admin.getRole() == 0 ? "快递管理员" : "快递员",
                    admin.getPhone(),
                    admin.getCardId()
            );
            ArrayList<Object> objects = new ArrayList<>();
            objects.add(adminWrap);
            String toJson = JSONUtil.toJson(new Message(200, "成功查寻到此快递！", objects));
            System.out.println(toJson);
            return toJson;
        }
        return JSONUtil.toJson(new Message(400, "未查到此快递！", null));
    }


    @ResponseBody("/admin/delete.do")
    public String adminDelete(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("id");
        Boolean delFlag = adminService.deleteAdmin(Integer.valueOf(id));
        if (delFlag) {
            String toJson = JSONUtil.toJson(new Message(200, "删除成功", null));
            System.out.println(toJson);
            return toJson;
        }
        String toJson = JSONUtil.toJson(new Message(400, "删除失败", null));
        System.out.println(toJson);
        return toJson;
    }


    @ResponseBody(value = "/admin/test.do")
    public String test(HttpServletRequest req, HttpServletResponse resp) {
        return "hi";
    }


    @ResponseBody("/admin/findByCardId.do")
    public String findByCardId(HttpServletRequest req, HttpServletResponse resp) {
        resp.setCharacterEncoding("utf-8");
        String cardId = req.getParameter("cardId");
        System.out.println(cardId);
        if (cardId.isEmpty()) {
            return JSONUtil.toJson(new Message(401, "身份号码为空！", null));
        }
        Admin admin = adminService.queryByCardId(cardId);
        if (null != admin&&admin.getAdminName()!=null&&!admin.getAdminName().isEmpty()) {
            System.out.println(admin.toString());
            AdminWrap adminWrap = new AdminWrap(
                    admin.getAdminId(),
                    admin.getAdminName(),
                    admin.getAdminPwd(),
                    admin.getLoginIP(),
                    FomatDateUtil.formatDate(admin.getLastTime()),
                    admin.getState() == 1 ? "启用" : "禁用",
                    admin.getRole() == 0 ? "快递管理员" : "快递员",
                    admin.getPhone(),
                    admin.getCardId()
            );
            ArrayList<Object> objects = new ArrayList<>();
            objects.add(adminWrap);
            String toJson = JSONUtil.toJson(new Message(200, "成功查寻到此快递员！", objects));
            System.out.println(toJson);
            return toJson;
        }
        String toJson = JSONUtil.toJson(new Message(400, "未查到此快递员！", null));
        System.out.println(toJson);
        return toJson;
    }


    @ResponseBody("/admin/findByUserName.do")
    public String admin(HttpServletRequest req, HttpServletResponse resp) {
        resp.setCharacterEncoding("utf-8");
        String userName = req.getParameter("userName");
        System.out.println(userName);
        if (null == userName||userName.isEmpty()) {
            return JSONUtil.toJson(new Message(401, "身份号码为空！", null));
        }
        Admin admin = adminService.queryByName(userName);
        if (null != admin&&admin.getAdminName()!=null&&!admin.getAdminName().isEmpty()) {
            System.out.println(admin.toString());
            AdminWrap adminWrap = new AdminWrap(
                    admin.getAdminId(),
                    admin.getAdminName(),
                    admin.getAdminPwd(),
                    admin.getLoginIP(),
                    FomatDateUtil.formatDate(admin.getLastTime()),
                    admin.getState() == 1 ? "启用" : "禁用",
                    admin.getRole() == 0 ? "快递管理员" : "快递员",
                    admin.getPhone(),
                    admin.getCardId()
            );
            ArrayList<Object> objects = new ArrayList<>();
            objects.add(adminWrap);
            String toJson = JSONUtil.toJson(new Message(200, "成功查寻到此用户名！", objects));
            System.out.println(toJson);
            return toJson;
        }
        String toJson = JSONUtil.toJson(new Message(400, "未查到此用户！", null));
        System.out.println(toJson);
        return toJson;
    }
}

